#!/usr/bin/env python3
# encoding=utf-8

import time
import datetime
import requests
from bs4 import BeautifulSoup
import logging
logger = logging.getLogger(__name__)

def get_codeinfo_from_network(codelist, dst, dend):
    # zs_000001  上证指数   cn_000001   平安银行
    # burl = 'https://q.stock.sohu.com/hisHq?code=zs_000001&start=20250104&end=20250124'
    burl = 'https://q.stock.sohu.com/hisHq?code=%s&start=%s&end=%s'
    retrycnt = 10
    rdatalist = {}
    for code in codelist:
        time.sleep(0.05)
        url = burl % (code, dst, dend)
        logger.debug(url)
        response = requests.get(url)  
        for i in range(0, retrycnt):
            if response.status_code != 200: 
                logger.info(f"{code} retry {i} Error: {response.status_code}") 
            else:
                break   
            time.sleep(0.1)
            response = requests.get(url)  
        if response.status_code != 200:  
            logger.info(f"{code} retry {retrycnt} Error: {response.status_code}") 
            continue
        data = response.json() 
        if 'hq' not in data[0]:
            logger.info(f"Error data: {data}")  
        dlist = []
        for one in data[0]['hq']:
            # logger.info(one)
            olist = []
            olist.append(one[0])
            olist.append(float(one[2]))
            dlist.insert(0, olist)
        rdatalist[code] = dlist
    # logger.info(rdatalist)
    return rdatalist

def get_codeinfo_from_emailinfo(emailinfo):
    if len(emailinfo) == 0:
        return None
    codedate = {}
    for one in emailinfo:
        if 'benchmark' not in one.keys() or 'date' not in one.keys():
            continue
        date = datetime.datetime.strptime(one['date'], "%Y-%m-%d")
        for code in one['benchmark']:
            if code not in codedate.keys():
                codedate[code] = []
                codedate[code].append(date)
                codedate[code].append(date)
            else:
                stday = codedate[code][0]
                endday = codedate[code][1]
                if date < stday:
                    codedate[code][0] = date
                elif date > endday:
                    codedate[code][1] = date
    # logger.info(codedate)

    codeinfo = {}
    for code, date in codedate.items():
        stday = date[0].strftime("%Y%m%d")
        endday = date[1].strftime("%Y%m%d")
        cinfo = get_codeinfo_from_network([code], stday, endday)
        codeinfo.update(cinfo)
    # logger.info(codeinfo)
    return codeinfo
                

